package com.dpiinc.TechPage.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.*
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.MenuItemCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.beiji.lib.pen.PenLog
import com.beiji.lib.pen.PenManager
import com.beiji.lib.pen.cache.PenCacheManager
import com.beiji.lib.pen.cache.PenCacheStatus
import com.beiji.lib.pen.cache.PenDotCacheHelper
import com.beiji.lib.pen.constants.PaletteColor
import com.beiji.lib.pen.model.DotUnit
import com.beiji.lib.pen.model.PenStroke
import com.beiji.lib.pen.ui.view.StrokeView
import com.czt.mp3recorder.Mp3Recorder
import com.dpiinc.TechPage.*
import com.dpiinc.TechPage.constants.FileType
import com.dpiinc.TechPage.menu.MenuConnectActionProvider
import com.dpiinc.TechPage.oss.OssFileManager
import com.dpiinc.TechPage.oss.UploadTask
import com.dpiinc.TechPage.pen.activity.HDRActivity
import com.dpiinc.TechPage.pen.activity.ReplayActivity
import com.dpiinc.TechPage.pen.dialog.ServiceDialog
import com.dpiinc.TechPage.pen.dialog.ServiceHintDialog
import com.dpiinc.TechPage.repository.EditNoteRepository
import com.dpiinc.TechPage.repository.Status
import com.dpiinc.TechPage.room.bean.NoteEntity
import com.dpiinc.TechPage.user.utils.PermissionUtils
import com.dpiinc.TechPage.user.utils.ShareHelper.showShareDialog
import com.dpiinc.TechPage.user.utils.StatusBarUtil
import com.dpiinc.TechPage.user.utils.ToastUtils
import com.dpiinc.TechPage.user.utils.ViewToBitmapUtil
import com.dpiinc.TechPage.utils.AppUtil
import com.dpiinc.TechPage.utils.AudioRecordHelper
import com.dpiinc.TechPage.utils.DateUtils
import com.dpiinc.TechPage.viewmodel.EditNoteViewModel
import com.dpiinc.TechPage.widget.*
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hwangjr.rxbus.RxBus
import com.yanzhenjie.permission.Action
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import kotlinx.android.synthetic.main.activity_edit_note.*
import kotlinx.android.synthetic.main.edit_note_record_audio_view.*
import java.util.*

/**
 * 编辑笔记页面
 * Created by X on 2018/7/3.
 * 
 * 书写界面
 */
class EditNoteActivity : AppCompatActivity(), View.OnClickListener {

    companion object {
        val TAG: String = EditNoteActivity::class.java.simpleName
        const val RECORD_DURATION_FORMAT_STR_LONG = "HH:mm:ss"
        const val RECORD_DURATION_FORMAT_STR_SHORT = "mm:ss"
        const val REQUEST_CODE_SELECT_LABEL = 10000
        const val ARG_NOTE_BEAN = "arg_note_bean"
    }

    private lateinit var eraserPicker: EraserPicker

    //    private var eraserPickerWindow: CustomPopWindow? = null
    private lateinit var paletteView: PaletteView
    private lateinit var paletteMarkView: PaletteView
    private var paletteViewWindow: CustomPopWindow? = null
    private var paletteViewMarkWindow: CustomPopWindow? = null
    private lateinit var viewModel: EditNoteViewModel
    private lateinit var connectActionProvider: MenuConnectActionProvider
    private var strokeColor: PaletteColor = PaletteColor.COLOR_0
    private var markColor: PaletteColor = PaletteColor.COLOR_4
    var isMkUser: Boolean = false
    var audioCount = 0
    var isShow: Boolean = false
    var isRevoke: Boolean = false
    var isOpen: Boolean = false
    var isOpenMk: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_note)
        initView()
        setStatusBarWhiteAndTextBlack()
        var note = intent.getSerializableExtra(ARG_NOTE_BEAN) as NoteEntity?
        note = note ?: NoteEntity(EditNoteViewModel.generateNoteId())
        if (note.recordFiles != null) {
            audioCount = note.recordFiles!!.size
        }
        if (note.dotFiles != null) {
            stroke_view.setBackgroundColor(Color.WHITE)
        }
        viewModel = ViewModelProviders.of(this, object : ViewModelProvider.Factory {
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                @Suppress("UNCHECKED_CAST")
                return EditNoteViewModel(note, application) as T
            }
        })[EditNoteViewModel::class.java]
        RxBus.get().register(this)
        bindView()
        viewModel.downloadFilesIfNotExists()
//        PenManager.instance.registerDataCallback(penCallback)
        if (audioCount > 0) {
            tv_audio_count.setText(audioCount.toString())
        }
        btn_intelligence_pen.isSelected = true
        setImageButtonHeight()
        //setPermissionXX(this)
    }

    private fun setPermissionXX(context: Context) {
        XXPermissions.with(context) // 申请单个权限
            .permission(com.hjq.permissions.Permission.WRITE_EXTERNAL_STORAGE) // 申请单个权限
            // .permission(Permission.Group.STORAGE)
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        Log.e("TAG", "获取部分权限成功，但部分权限未正常授予")
                        //toast("获取部分权限成功，但部分权限未正常授予");
                        return
                    }
                    Log.e("TAG", "获取录音和日历权限成功")
                    //toast("获取录音和日历权限成功");
                }

                override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        Log.e("TAG", "被永久拒绝授权，请手动授予录音和日历权限")
                        //toast("被永久拒绝授权，请手动授予录音和日历权限");
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(context, permissions)
                    } else {
                        Log.e("TAG", "获取录音和日历权限失败")
                        //toast("获取录音和日历权限失败");
                    }
                }
            })
    }


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        PenLog.e("onNewIntent")
    }

    @SuppressLint("InflateParams")
    private fun initView() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        toolbar.setNavigationOnClickListener { onBackPressed() }
        tv_title.setOnClickListener(this)
        btn_record_audio.setOnClickListener(this)
        btn_recording.setOnClickListener(this)
        btn_eraser.setOnClickListener(this)
        btn_eraser_big_icon.setOnClickListener(this)
        btn_eraser_middle_icon.setOnClickListener(this)
        btn_eraser_small_icon.setOnClickListener(this)
        tv_eraser_clear_notes.setOnClickListener(this)
        btn_stroke_color.setOnClickListener(this)
        btn_intelligence_pen.setOnClickListener(this)
        eraserPicker = LayoutInflater.from(this).inflate(R.layout.eraser_picker_layout, null, false) as EraserPicker
//        eraserPicker.onEraserPicked = {
//            toastIfDebug("$it picked.")
//            stroke_view.setEraserRadius(it)
//        }
        stroke_view.setEraserRadius(15.0f)
        eraserPicker.select(1)
        paletteView = PaletteView(this)
        paletteView.onColorPicked = {
            //            toastIfDebug("${it.value} picked")
            paletteViewWindow?.dismiss()
            isOpen = false
            setIntelligenceColor(it)
        }
        paletteMarkView = PaletteView(this, 4)
        paletteMarkView.onColorPicked = {
            //            toastIfDebug("${it.value} picked")
            paletteViewMarkWindow?.dismiss()
            isOpenMk = false
            setMarkColor(it)
        }
        PenLog.e("initView -> setStrokeColor(PaletteColor.COLOR_0)")
        //设置默认颜色
        setIntelligenceColor(PaletteColor.COLOR_0)
        setMarkColor(PaletteColor.COLOR_4)
        show_eraser_choose_layout.visibility = View.GONE
        isShow = false
        btn_eraser_middle_icon.isSelected = true
    }

    private fun setMarkColor(strokeColor: PaletteColor) {
        stroke_view.setMarkColor(strokeColor, true)
        markColor = strokeColor
        val colorDrawable = when (strokeColor) {
            PaletteColor.COLOR_0 -> R.drawable.mk_pen_color_selector0
            PaletteColor.COLOR_1 -> R.drawable.mk_pen_color_selector1
            PaletteColor.COLOR_2 -> R.drawable.mk_pen_color_selector2
            PaletteColor.COLOR_3 -> R.drawable.mk_pen_color_selector3
            PaletteColor.COLOR_4 -> R.drawable.mk_pen_color_selector4
            PaletteColor.COLOR_5 -> R.drawable.mk_pen_color_selector5
            PaletteColor.COLOR_6 -> R.drawable.mk_pen_color_selector6
            PaletteColor.COLOR_7 -> R.drawable.mk_pen_color_selector7
            else -> R.drawable.mk_pen_color_selector4
        }
        btn_stroke_color.setImageResource(colorDrawable)
    }

    private fun setIntelligenceColor(color: PaletteColor) {
        stroke_view.setStrokeColor(color, true)
        strokeColor = color
        val colorDrawable = when (color) {
            PaletteColor.COLOR_0 -> R.drawable.intelligence_pen_color_selector0
            PaletteColor.COLOR_1 -> R.drawable.intelligence_pen_color_selector1
            PaletteColor.COLOR_2 -> R.drawable.intelligence_pen_color_selector2
            PaletteColor.COLOR_3 -> R.drawable.intelligence_pen_color_selector3
            PaletteColor.COLOR_4 -> R.drawable.intelligence_pen_color_selector4
            PaletteColor.COLOR_5 -> R.drawable.intelligence_pen_color_selector5
            PaletteColor.COLOR_6 -> R.drawable.intelligence_pen_color_selector6
            PaletteColor.COLOR_7 -> R.drawable.intelligence_pen_color_selector7
            else -> R.drawable.intelligence_pen_color_selector0
        }
        btn_intelligence_pen.setImageResource(colorDrawable)
    }

    private fun bindView() {
        viewModel.note.noteName?.let {
            if (it.isNotEmpty()) {
                tv_title.text = viewModel.note.noteName
            }
        }
        viewModel.networkState.observe(this, Observer {
            it ?: return@Observer
            toastIfDebug(it.toString())
            AWLog.e(TAG, it.toString())
            when (it.status) {
                Status.SUCCESS -> {
                    if (it.tag == EditNoteRepository.OPERATION_DELETE) {
                        ToastUtils.showCenterTip(this, getString(R.string.toast_edit_note_delete_success))
                    }
//                    else {
//                        if (viewModel.needRecognize) {
//                            HdrHelper.reportHdrResult(viewModel.note.noteId)
//                        }
//                    }
                    LoadingView.dismissLoadingView()
                    finish()
                }
                Status.RUNNING -> {
                }
                Status.FAILED -> {
                    if (it.tag == EditNoteRepository.OPERATION_DELETE) {
                        ToastUtils.showCenterTip(this, getString(R.string.toast_edit_note_delete_failed))
                        toastIfDebug(it.msg.toString())
                    } else {
                        ToastUtils.showCenterTip(this, getString(R.string.toast_edit_note_save_failed))
                    }
                    //TODO 提交失败处理
                    LoadingView.dismissLoadingView()
//                    finish()
                }
            }
        })
        viewModel.downloadState.observe(this, Observer {
            it ?: return@Observer
            AWLog.e(TAG, "downloadState$it.toString()")
            when (it.status) {
                Status.SUCCESS -> {
                    LoadingView.dismissLoadingView()
                    startCache()
                }
                Status.RUNNING -> {
                    LoadingView.dismissLoadingView()
                    LoadingView.createLoadingViewAndShow(this, 0, it.msg)
                }
                Status.FAILED -> {
                    //TODO 这里要区分什么文件下载失败，如果是笔迹文件下载失败，才不需要重绘..
                    viewModel.needRedraw = false
                    ToastUtils.showCenterTip(this, getString(R.string.toast_download_files_failed))
                    LoadingView.dismissLoadingView()
                    startCache()
                }
            }
        })
    }

    private fun startCache() {
        stroke_view.startCache(viewModel.note.noteId)
        if (viewModel.needRedraw) {
            LoadingView.createLoadingViewAndShow(this, 0, getString(R.string.edit_note_redrawing))
            //TODO Yang
            stroke_view.drawStrokeFromCacheFile {
                LoadingView.dismissLoadingView()
            }
        }
        PenCacheManager.instance.getCurrentCache()?.liveCacheStatus?.observe(this, Observer {
            it ?: return@Observer
            when (it.status) {
                PenCacheStatus.FIRST_STROKE -> {
                    Log.i(TAG, "startCache: PenCacheStatus.FIRST_STROKE")
                    //笔记平均页数
                    val cal = Calendar.getInstance()
                    val properties = Properties()
                    properties.setProperty("hour", cal.get(Calendar.HOUR_OF_DAY).toString())
                    properties.setProperty("minute", cal.get(Calendar.MINUTE).toString())
                    properties.setProperty("second", cal.get(Calendar.SECOND).toString())

                    viewModel.hasEdited = true
                    viewModel.hasNewStrokes = true
//                    val dotFile = it.cacheData.getCacheFile()
//                    val dotUploadTask = UploadTask(viewModel.note.noteId, FileType.DOT_FILE).apply {
//                        fileName = dotFile.name
//                        filePath = dotFile.path
//                        time = DateUtils.getCurrentTimeMillis()
//                    }
//                    viewModel.addUpload(dotUploadTask)
                    eraser_revoke_view.setOnClickListener(this)
                    eraser_revoke_view.setBackgroundResource(R.drawable.ic_eraser_selected)
                }
                PenCacheStatus.NEW_STROKE -> {
                    Log.i(TAG, "startCache: PenCacheStatus.NEW_STROKE")
                    eraser_revoke_view.setOnClickListener(this)
                    eraser_revoke_view.setBackgroundResource(R.drawable.ic_eraser_selected)
                    viewModel.hasEdited = true
                    viewModel.hasNewStrokes = true
                    viewModel.needRecognize = true
                }
                PenCacheStatus.CLEARALL -> {//清空笔记
                    val previewFile = it.cacheData.getPreviewFile()
                    val previewTask = UploadTask(viewModel.note.noteId, FileType.IMG_FILE).apply {
                        fileName = previewFile.name
                        filePath = previewFile.path
                        time = DateUtils.getCurrentTimeMillis()
                    }
                    OssFileManager.instance.deleteStroke(previewTask)

                    val cachefile = it.cacheData.getCacheFile()
                    val cacheTask = UploadTask(viewModel.note.noteId, FileType.DOT_FILE).apply {
                        fileName = cachefile.name
                        filePath = cachefile.path
                        time = DateUtils.getCurrentTimeMillis()
                    }
                    OssFileManager.instance.deleteStroke(cacheTask)
                    viewModel.clear()
                    it.cacheData.clearLoacl()
                    stroke_view.setBackgroundResource(R.drawable.note_edit_bg)
//                        viewModel.addUpload(previewUploadTask)
//                    viewModel.note.imageFiles = null
                    viewModel.hasEdited = true

                }
                PenCacheStatus.REMOVE_LAST -> {//删除最后一笔
                    LoadingView.createLoadingViewAndShow(this, 0, getString(R.string.edit_note_revokeing))
//                        stroke_view.drawStrokeFromCacheFile(false) {
                    stroke_view.drawStrokeFromCacheFile {
                        isRevoke = false
                        LoadingView.dismissLoadingView()
                    }
                }
                PenCacheStatus.FINISHED -> {
                    Log.i(TAG, "startCache: PenCacheStatus.FINISHED")
                    if (viewModel.hasNewStrokes) {
                        Log.i(TAG, "startCache: viewModel.hasNewStrokes")
                        val previewFile = it.cacheData.getPreviewFile()
                        val previewUploadTask = UploadTask(viewModel.note.noteId, FileType.IMG_FILE).apply {
                            fileName = previewFile.name
                            filePath = previewFile.path
                            time = DateUtils.getCurrentTimeMillis()
                        }
                        viewModel.addUpload(previewUploadTask)
                        val dotFile = it.cacheData.getCacheFile()
                        val dotUploadTask = UploadTask(viewModel.note.noteId, FileType.DOT_FILE).apply {
                            fileName = dotFile.name
                            filePath = dotFile.path
                            time = DateUtils.getCurrentTimeMillis()
                        }
                        viewModel.addUpload(dotUploadTask)
                    }

                    if (!viewModel.saveToServer()) {
                        LoadingView.dismissLoadingView()
                        Log.i(TAG, "startCache: LoadingView.dismissLoadingView()")
                        finish()
                    }
                }
                else -> {
                }
            }
        })
    }

    override fun onResume() {
        super.onResume()
        PenManager.instance.registerDataCallback(penCallback)
        if (isHasAlwaysPermission) {
            finish()
        }
    }

    private val penCallback: (DotUnit) -> Boolean = {
        Log.i(TAG, "数据：$it.toString()")
        if (PenCacheManager.instance.isOnCache) {
            if (btn_eraser.isSelected) {
                btn_eraser.isSelected = false
                show_eraser_choose_layout.visibility = View.GONE
                isShow = false
                if (isMkUser) {
                    btn_stroke_color.isSelected = true
                    stroke_view.setEditMode(StrokeView.EditMode.MARK)
                } else {
                    btn_intelligence_pen.isSelected = true
                    stroke_view.setEditMode(StrokeView.EditMode.STROKE)
                }
                setImageButtonHeight()
            }
            if (isMkUser) {
                it.actionType = PenStroke.ACTION_MARK
                PenDotCacheHelper.acttype = PenStroke.ACTION_MARK
                setMarkColor(markColor)
            } else {
                it.actionType = PenStroke.ACTION_STROKE
                PenDotCacheHelper.acttype = PenStroke.ACTION_STROKE
                setIntelligenceColor(strokeColor)
            }

            //把在页面注册回调成功之前缓存下来的点绘制出来
            PenManager.instance.drainCachedDots { cachedDot ->
                PenDotCacheHelper.cacheDot(cachedDot)
                stroke_view.drawDot(cachedDot)
            }
            if (!isRevoke)
                stroke_view.drawDot(it)
            true
        } else {
            //在startCache之前把点先缓存下来
            PenManager.instance.cacheDotTemporary(it)
            false
        }
    }

    override fun onDestroy() {
//        stroke_view.endCache()
        //恢复默认颜色，避免下次连接成功后直接书写，在重新设置默认颜色之前书写的笔记使用了上一次的颜色
        setIntelligenceColor(PaletteColor.COLOR_0)
        setMarkColor(PaletteColor.COLOR_0)
        isMkUser = false
        RxBus.get().unregister(connectActionProvider)
        PenManager.instance.unRegisterDataCallback(penCallback)
        super.onDestroy()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_edit_note, menu)
        val connectMenu = menu?.findItem(R.id.menu_connect)
                ?: return super.onPrepareOptionsMenu(menu)
        connectActionProvider = MenuItemCompat.getActionProvider(connectMenu) as MenuConnectActionProvider
        RxBus.get().register(connectActionProvider)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onMenuOpened(featureId: Int, menu: Menu): Boolean {
        menu?.let {
            if (it.javaClass.simpleName.equals("MenuBuilder", true)) {
                try {
                    val method = it.javaClass.getDeclaredMethod("setOptionalIconsVisible", java.lang.Boolean.TYPE)
                    method.isAccessible = true
                    method.invoke(menu, true)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        return super.onMenuOpened(featureId, menu)
    }

    override fun onClick(v: View?) {
        v ?: return
        when (v.id) {
            R.id.tv_title -> {
                val selectLabelIntent = Intent(this@EditNoteActivity, InputTitleActivity::class.java)
                val arguments = InputTitleActivity.ResultData(viewModel.note.noteName, viewModel.note.label)
                selectLabelIntent.putExtra(InputTitleActivity.ARG_RESULT_DATA, arguments)
                startActivityForResult(selectLabelIntent, REQUEST_CODE_SELECT_LABEL)
            }
            R.id.btn_intelligence_pen -> {
                isOpenMk = false
                paletteViewMarkWindow?.dismiss()
//                val windowWidth = screenWidth - AppUtil.dp2px(20f).toInt()
                if (!isOpen && btn_intelligence_pen.isSelected) {
                    isOpen = true
                    paletteViewWindow = CustomPopWindow.PopupWindowBuilder(this)
                            .setView(paletteView)
                            .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                            .create()
                            .showOnTopOf(buttons_layout, AppUtil.dp2px(-2f).toInt())
                } else {
                    isOpen = false
                    paletteViewWindow?.dismiss()
                }
                stroke_view.setEditMode(StrokeView.EditMode.STROKE)
                btn_eraser.isSelected = false
                show_eraser_choose_layout.visibility = View.GONE
                isShow = false
                btn_stroke_color.isSelected = false
                btn_intelligence_pen.isSelected = true
                isMkUser = false
                setImageButtonHeight()
            }
            R.id.btn_stroke_color -> {
                isOpen = false
                paletteViewWindow?.dismiss()
//                val windowWidth = screenWidth - AppUtil.dp2px(20f).toInt()
                if (!isOpenMk && btn_stroke_color.isSelected) {
                    isOpenMk = true
                    paletteViewMarkWindow = CustomPopWindow.PopupWindowBuilder(this)
                            .setView(paletteMarkView)
                            .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                            .create()
                            .showOnTopOf(buttons_layout, AppUtil.dp2px(-2f).toInt())
                } else {
                    isOpenMk = false
                    paletteViewMarkWindow?.dismiss()
                }
                btn_stroke_color.isSelected = true
                btn_intelligence_pen.isSelected = false
                stroke_view.setEditMode(StrokeView.EditMode.MARK)
                btn_eraser.isSelected = false
                show_eraser_choose_layout.visibility = View.GONE
                isShow = false
                isMkUser = true
                setImageButtonHeight()
            }
            R.id.btn_eraser -> {
                isOpen = false
                isOpenMk = false
                paletteViewWindow?.dismiss()
                paletteViewMarkWindow?.dismiss()
                stroke_view.setEditMode(StrokeView.EditMode.ERASER)
                Log.i(TAG, "getSelectEraserRadius: " + eraserPicker.getSelectEraserRadius());
                btn_eraser.isSelected = true
                if (isShow) {
                    show_eraser_choose_layout.visibility = View.GONE
                    isShow = false
                } else {
                    show_eraser_choose_layout.visibility = View.VISIBLE
                    isShow = true
                }
                btn_stroke_color.isSelected = false
                btn_intelligence_pen.isSelected = false

                setImageButtonHeight()
            }
            R.id.tv_eraser_clear_notes -> {//清空笔记
                val builder = CommDialog.Builder()
                builder.setTitle(getString(R.string.clear_note_dialog_title))
                        .setMessage(getString(R.string.clear_note_dialog_message))
                        .setLeftButton(getString(R.string.clear_note_dialog_left_button_text), DialogInterface.OnClickListener { dialogInterface, _ ->
                            dialogInterface.dismiss()
                        })
                        .setRightButton(getString(R.string.clear_note_dialog_right_button_text), DialogInterface.OnClickListener { dialogInterface, _ ->
                            dialogInterface.dismiss()

                            stroke_view.clearAllStroke(true)
                            PenCacheManager.instance.removeStroke()
                            eraser_revoke_view.setOnClickListener(null)
                            eraser_revoke_view.setBackgroundResource(R.drawable.ic_eraser_unselected)

                        })
                        .setRightButtonTextColor(ContextCompat.getColor(this, R.color.clear_note_dialog_btn_text_color_right))
                        .setLeftButtonTextColor(ContextCompat.getColor(this, R.color.clear_note_dialog_btn_text_color_left))
                builder.build().show(supportFragmentManager)
            }
            R.id.eraser_revoke_view -> {//撤销上一步
                isRevoke = true
                eraser_revoke_view.setOnClickListener(null)
                eraser_revoke_view.setBackgroundResource(R.drawable.ic_eraser_unselected)
                PenCacheManager.instance.removeLastStroke()
            }
            R.id.btn_eraser_small_icon -> {
                eraserPicker.select(0)
                btn_eraser_small_icon.isSelected = true
                btn_eraser_middle_icon.isSelected = false
                btn_eraser_big_icon.isSelected = false
                stroke_view.setEraserRadius(eraserPicker.getSelectEraserRadius())
                show_eraser_choose_layout.visibility = View.GONE
                isShow = false
            }
            R.id.btn_eraser_middle_icon -> {
                eraserPicker.select(1)
                btn_eraser_small_icon.isSelected = false
                btn_eraser_middle_icon.isSelected = true
                btn_eraser_big_icon.isSelected = false
                stroke_view.setEraserRadius(eraserPicker.getSelectEraserRadius())
                show_eraser_choose_layout.visibility = View.GONE
                isShow = false
            }
            R.id.btn_eraser_big_icon -> {
                eraserPicker.select(2)
                btn_eraser_small_icon.isSelected = false
                btn_eraser_middle_icon.isSelected = false
                btn_eraser_big_icon.isSelected = true
                stroke_view.setEraserRadius(eraserPicker.getSelectEraserRadius())
                show_eraser_choose_layout.visibility = View.GONE
                isShow = false
            }
            R.id.btn_record_audio -> {
                show_eraser_choose_layout.visibility = View.GONE
                isShow = false
                if (checkRecordAudioPermission()) {
                    startRecord()
                }

            }
            R.id.btn_recording -> {
                show_eraser_choose_layout.visibility = View.GONE
                isShow = false
                endRecord()
            }
        }
    }

    private fun setImageButtonHeight() {
        val erasParams = btn_eraser.layoutParams as LinearLayout.LayoutParams
        val intellParams = btn_intelligence_pen.layoutParams as LinearLayout.LayoutParams
        val strokeParams = btn_stroke_color.layoutParams as LinearLayout.LayoutParams
        if (btn_eraser.isSelected) {
            erasParams.height = this.getResources().getDimension(R.dimen.dp90).toInt()
            btn_eraser.layoutParams = erasParams

            intellParams.height = resources.getDimension(R.dimen.dp54).toInt()
            btn_intelligence_pen.layoutParams = intellParams
            strokeParams.height = this.getResources().getDimension(R.dimen.dp54).toInt()
            btn_stroke_color.layoutParams = strokeParams
        } else if (btn_intelligence_pen.isSelected) {
            intellParams.height = this.getResources().getDimension(R.dimen.dp85).toInt()
            btn_intelligence_pen.layoutParams = intellParams

            erasParams.height = this.getResources().getDimension(R.dimen.dp54).toInt()
            btn_eraser.layoutParams = erasParams
            strokeParams.height = resources.getDimension(R.dimen.dp54).toInt()
            btn_stroke_color.layoutParams = strokeParams
            setIntelligenceColor(strokeColor)
        } else if (btn_stroke_color.isSelected) {
            strokeParams.height = this.getResources().getDimension(R.dimen.dp88).toInt()
            btn_stroke_color.layoutParams = strokeParams

            erasParams.height = this.getResources().getDimension(R.dimen.dp54).toInt()
            btn_eraser.layoutParams = erasParams
            intellParams.height = this.getResources().getDimension(R.dimen.dp54).toInt()
            btn_intelligence_pen.layoutParams = intellParams
            setMarkColor(markColor)
        }
    }

    private fun endRecord(onExit: Boolean = false) {
        setImageButtonHeight()
        rl_record.visibility = View.VISIBLE
        btn_recording.visibility = View.GONE
        LoadingView.createLoadingViewAndShow(this, 0, getString(R.string.label_edit_note_saving))
        if (AudioRecordHelper.getState() == Mp3Recorder.State.RECORDING) {
            val result = viewModel.endRecordAudio()
            if (result == null) {
                if (!onExit)
                    ToastUtils.showCenterTip(this@EditNoteActivity, getString(R.string.toast_record_audio_error))
            } else {
                if (!onExit) {
                    audioCount++
                    tv_audio_count.text = audioCount.toString()
                    ToastUtils.showCenterRecordTip(this@EditNoteActivity)
                }
                viewModel.hasEdited = true
            }
        }
        LoadingView.dismissLoadingView()
//        Timer().schedule(object : TimerTask() {
//            override fun run() {
//                if (AudioRecordHelper.getState() == Mp3Recorder.State.RECORDING) {
//                    val result = viewModel.endRecordAudio()
//                    if (result == null) {
//                        if (!onExit)
//                            launch(UI) {
//                                ToastUtils.showCenterTip(this@EditNoteActivity, getString(R.string.toast_record_audio_error))
//                            }
//                    } else {
//                        if (!onExit) {
//                            audioCount++
//                            launch(UI) {
//                                tv_audio_count.setText(audioCount.toString())
//                                ToastUtils.showCenterRecordTip(this@EditNoteActivity)
//                            }
//                        }
//                        viewModel.hasEdited = true
//                    }
//                }
//                LoadingView.dismissLoadingView()
//            }
//        }, 1200)
    }

    private fun startRecord() {
        if (AudioRecordHelper.getState() != Mp3Recorder.State.RECORDING) {
            val audioFile = viewModel.startRecordAudio(onAudioRecordingCallback)
            if (audioFile != null) {
                rl_record.visibility = View.GONE
                btn_recording.visibility = View.VISIBLE
            } else {
                ToastUtils.showCenterTip(this, getString(R.string.toast_record_audio_error))
            }
        }
    }

    private fun checkRecordAudioPermission(): Boolean {
        if (AndPermission.hasPermissions(this, Permission.RECORD_AUDIO)) {
            return true
        }

//        if (AndPermission.hasAlwaysDeniedPermission(this, Permission.RECORD_AUDIO)) {
//            ToastUtils.showCenterTip(this, getString(R.string.toast_ask_for_record_audio_permission))
//            AndPermission.with(this)
//                    .runtime()
//                    .setting()
//                    .start()
//            return false
//        }


        Handler().postDelayed({
            if (showHintDialog) {
                ServiceHintDialog.ShowDialog(this, resources.getString(R.string.service_dialog_title_hint),
                        resources.getString(R.string.service_dialog_msg_hint3))
            }
        }, 250)


        showHintDialog = true;
        AndPermission.with(this)
                .runtime()
                .permission(Permission.RECORD_AUDIO)

                //拒绝一次之后的提示
                .rationale { context, _, executor ->
                    executor.execute()
                }
                //申请被拒绝
                .onDenied { permissions ->
                    PenLog.e("onDenied")
                    // 用户拒绝权限
                    showHintDialog = false;
                    ServiceHintDialog.dismissDialog()
                    //被拒绝，且选择了不再提醒之后，需要提示用户去设置页面手动打开
                    if (AndPermission.hasAlwaysDeniedPermission(this, permissions)) {
                        ServiceDialog.ShowDialog(this, resources.getString(R.string.toast_ask_for_record_audio_permission),
                                resources.getString(R.string.toast_ask_for_record_audio_permission1), ServiceDialog.OnClickEditListener {
                            ServiceDialog.dismissDialog()
                            isHasAlwaysPermission = true
                            AndPermission.with(this)
                                    .runtime()
                                    .setting()
                                    .onComeback {
                                        isHasAlwaysPermission = false;
                                        if (!AndPermission.hasPermissions(this, Permission.RECORD_AUDIO)) {
                                            finish()
                                        }
                                    }.start()
                        })
                    }
                }
                .onGranted {
                    //用户给权限了
                    ServiceHintDialog.dismissDialog()
                    startRecord()
                }.start()

        return false
    }

    private var showHintDialog = true
    private var isHasAlwaysPermission = false

    private val onAudioRecordingCallback = object : Mp3Recorder.Callback {
        override fun onReset() {}
        override fun onResume() {}
        override fun onPause() {}
        override fun onMaxDurationReached() {}
        override fun onRecording(duration: Double, volume: Double) {
            val durationFormatStr = if (duration.toLong() > 3600 * 1000) {//大于一小时
                RECORD_DURATION_FORMAT_STR_LONG
            } else {
                RECORD_DURATION_FORMAT_STR_SHORT
            }
            val durationStr = DateUtils.getDurationString(duration.toLong(), durationFormatStr)
            btn_recording.text = durationStr
        }

        override fun onStart() {
            AWLog.e(TAG, "record start.")
        }

        override fun onStop(action: Int) {
            AWLog.e(TAG, "record end.")
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_CODE_SELECT_LABEL -> {
                if (resultCode == Activity.RESULT_OK) {
                    data?.let {
                        val resultData = data.getSerializableExtra(InputTitleActivity.ARG_RESULT_DATA) as InputTitleActivity.ResultData
                        if (resultData.noteName != null && resultData.noteName.isNotEmpty()) {
                            viewModel.note.noteName = resultData.noteName
                            tv_title.text = viewModel.note.noteName
                        }
                        viewModel.note.label = resultData.labels
                        viewModel.hasEdited = true
                    }
                }
            }
        }
    }

    override fun onPause() {
        super.onPause()
        if (viewModel.hasEdited && PenCacheManager.instance.isOnCache) {
            PenCacheManager.instance.drainCache()
            viewModel.saveToLocal()
        }
    }

    override fun onBackPressed() {
        Log.i(TAG, "onBackPressed: ")
        //笔记平均书写时长

        viewModel.note.modifyTime = viewModel.note.modifyTime + 1
        //笔记平均页数
        val properties = Properties()
        properties.setProperty("userId", UserManager.getUserId())
        properties.setProperty("noteId", viewModel.note.noteId)
        properties.setProperty("page", stroke_view.pageMap.size().toString())

        endRecord(true)
        stroke_view.endCache()
        LoadingView.createLoadingViewAndShow(this, 0, getString(R.string.label_edit_note_saving))
//        super.onBackPressed()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_delete -> {
                val builder = CommDialog.Builder()
                builder.setTitle(getString(R.string.delete_note_dialog_title))
                        .setMessage(getString(R.string.delete_note_dialog_message))
                        .setLeftButton(getString(R.string.delete_note_dialog_left_button_text), DialogInterface.OnClickListener { dialogInterface, _ ->
                            dialogInterface.dismiss()
                        })
                        .setRightButton(getString(R.string.delete_note_dialog_right_button_text), DialogInterface.OnClickListener { dialogInterface, _ ->
                            dialogInterface.dismiss()
                            viewModel.delete()
                        })
                        .setRightButtonTextColor(ContextCompat.getColor(this, R.color.comm_dialog_btn_text_color_important))
                builder.build().show(supportFragmentManager)
            }
            R.id.menu_replay -> {
                LoadingView.createLoadingViewAndShow(this, 0, null)
                PenCacheManager.instance.drainCache {
                    LoadingView.dismissLoadingView()
                    val intent = Intent(this, ReplayActivity::class.java)
                    intent.putExtra(ReplayActivity.ARG_NOTE_KEY, viewModel.note.noteId)
                    startActivity(intent)
                }
            }
            R.id.menu_HDR -> {
                LoadingView.createLoadingViewAndShow(this, 0, null)
                PenCacheManager.instance.drainCache {
                    LoadingView.dismissLoadingView()
                    val intent = Intent(this, HDRActivity::class.java)
                    intent.putExtra(ReplayActivity.ARG_NOTE_KEY, viewModel.note.noteId)
                    intent.putExtra(HDRActivity.ARG_NEED_NAME, viewModel.note.noteName)
                    intent.putExtra(HDRActivity.ARG_NEED_RECOGNIZE, viewModel.needRecognize)
                    startActivity(intent)
                    //在手写识别页面会提交识别结果，所以退出编辑页面的时候就没必要再识别一次了，其实这里手写识别页面得优化一下，返回一个识别成功或者识别的结果，如果失败了，退出编辑页面的时候还是要重新识别提交一下。
                    viewModel.needRecognize = false

                }
            }
            R.id.menu_share -> {
                LoadingView.createLoadingViewAndShow(this, 0, null)
                PenCacheManager.instance.drainCache {
                    val bitmapPathList: ArrayList<String> = PenCacheManager.instance.getPenStrokeBitmapPathList(viewModel.note.noteId)
                    setModifyTimeForShare()
                    ViewToBitmapUtil.generateAllBitmap(this@EditNoteActivity, bitmapPathList)

                    PenCacheManager.instance.getCurrentCache()?.readStrokesFromFile {
                        LoadingView.dismissLoadingView()
                        if (it.isEmpty()) {
                            ToastUtils.showCenterTip(this, getString(R.string.toast_replay_empty_stroke))
                            LoadingView.dismissLoadingView()
                            return@readStrokesFromFile
                        } else {
                            checkPermissionShowDialog(bitmapPathList)
                        }
                    }
                }
            }
            R.id.menu_audio -> {
                LoadingView.createLoadingViewAndShow(this, 0, null)
                PenCacheManager.instance.drainCache {
                    LoadingView.dismissLoadingView()
                    val intent = Intent(this, PlayAudioActivity::class.java)
                    intent.putExtra(PlayAudioActivity.ARG_NOTE_KEY, viewModel.note.noteId)
                    startActivity(intent)
                }
            }
        }
        return true
    }

    private fun setModifyTimeForShare() {
        if (viewModel.hasEdited) {
            ViewToBitmapUtil.setShareTime(DateUtils.getCurrentTimeMillis());
        } else {
            ViewToBitmapUtil.setShareTime(viewModel.note.modifyTime);
        }
        ViewToBitmapUtil.setShareTitle(viewModel.note.noteName)
    }

    private fun checkPermissionShowDialog(bitmapPathList: ArrayList<String>) {

        val granted = Action<List<String>> {
            showShareDialog(this@EditNoteActivity, bitmapPathList,"")
        }
        val denied = Action<List<String>> {
            ToastUtils.showTopTip(this@EditNoteActivity, getString(R.string.no_authority_share))
            Log.d(TAG, "onAction denied")
        }
    //    if (PermissionUtils.checkWRITE_EXTERNAL_STORAGE(this@EditNoteActivity, granted, denied)) {
            showShareDialog(this@EditNoteActivity, bitmapPathList,"")
   //     }

    }

    fun setStatusBarWhiteAndTextBlack() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StatusBarUtil.setStatusBarColor(this, R.color.white)
            StatusBarUtil.StatusBarLightMode(this) //设置白底黑字
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
    }
}
